<?php
/**
 * Created by PhpStorm.
 * User: liyang
 * Date: 2017/12/6  Time: 下午2:30
 * Description: 风险测评
 */

use Service\AnswerService;
use Service\UserService;
use Illuminate\Database\Capsule\Manager as DB;
use Wxxiong6\WxxLogger\WxxLogger as Logger;

class RiskratingController extends BaseController
{


    /**
     * 返回评测题库
     */
    public function getsubjectsAction()
    {
        $type = $this->getRequest()->getParam('type');

        if (empty($type)) {
            $this->callback('', MISS_REQUEST_PARAMS, '缺少参数,参数为空');
        }

        $question = QuestionModel::select('param')->where('type', $type)->orderBy('id', 'desc')->first();
        $questionArr = json_decode($question->param, true);
        $param = [];
        foreach ($questionArr as $v) {
            foreach ($v['questions'] as $item) {
                $item['part_name'] = $v['part_name'];
                $param[] = $item;
            }
        }

        $this->callback($param);
    }

    /**
     * 答案提交接口，返回评测结果
     */
    public function postanswerAction()
    {
        $uid = $this->header['uid'];//用户ID
        $type = $this->getRequest()->getParam('type');
        $answer = $this->getRequest()->getParam('answer');

        if (empty($type) || empty($answer)) {
            $this->callback('', MISS_REQUEST_PARAMS, '缺少参数,参数为空');
        }

        $questionId = QuestionModel::select('id')->where('type', $type)->orderBy('id', 'desc')->first();

        $answerArr = json_decode($answer, true);

        try {
            $score = AnswerService::getInstance()->answerRes($answerArr);
        } catch (Exception $exception) {
            $this->callback('', '', $exception->getMessage());
        }

        //开启事务
        DB::beginTransaction();
        try {

            $userInfo = UserModel::select(UserService::getInstance()->user_fileds)->where('id', $uid)->first();

            if (empty($userInfo['id'])) {
                $this->callback([], MISS_REQUEST_PARAMS, '没有此用户');
            }

            $eid = UserService::getInstance()->saveEvaluation($userInfo, $score, $answer);

            if (!$eid) {
                throw new Exception("问卷表操作失败或者获取该ID失败");
            }
            $userInfo->e_id = $eid;
            $saveUser = $userInfo->save();

            if (!$saveUser) {
                throw new Exception("user表更新e_id失败");
            }
            $answerRes = [];
            $answerRes['score'] = $score;
            $answerRes['question_id'] = $questionId['id'];
            $answerRes['u_id'] = $uid;
            $answerRes['answer'] = $answer;
            $answerRes['created_at'] = date('Y-m-d H:i:s');
            $insAnswer = AnswerModel::create($answerRes);
            if (!$insAnswer) {
                throw new Exception("answer表保存测评结果失败");
            }
            $gradeArr = UserService::getInstance()->getGrade($score);
            $gradeArr['score'] = $score . '分';
            $gradeArr['datetime'] = $answerRes['created_at'];
            //处理私募适当性风险异动
            $privateRisk = UserService::getInstance()->privateRiskChange($gradeArr['grade_int'], $uid);
            //如果产生适当性处理则更新缓存
            if ($privateRisk) {
                UserService::getInstance()->updateUserInfoCache([
                    'id' => $uid,
                    'grade_int' => $gradeArr['grade_int'],
                    'grade' => $gradeArr['grade_int'],
                    'risklevel' => $gradeArr['risklevel'],
                    'description' => $gradeArr['description']
                ]);
            }

            DB::commit();//提交事务
            $this->callback($gradeArr);
        } catch (Exception $e) {
            DB::rollback();//事务回滚
            Logger::error('用户ID：' . $uid . ',错误信息：' . $e->getMessage());
            $this->callback('', APP_REQUEST_SUCCESS, $e->getMessage());
        }

    }

}